const express = require("express");
const uuid = require("uuid");
const path = require("path");
const fs = require("fs");
const  multer = require("multer");
const {html2pdf} = require("./utils");

let app = express();

let multerObj = multer({dest:path.join(__dirname,'public/upload')});

app.use(multerObj.any());

app.use(express.urlencoded({extended:false}));

app.use(express.json({
    limit:"10mb"
}));
// 设置静态资源目录
app.use(express.static(path.join(__dirname,'public')));

app.post("/html2pdf",async function(req,res){
    var params = req.body;
    let htmlFile = req.body.file;
    let htmlPath = "";
    if(!params.html && (!htmlFile || htmlFile.type !== "Buffer")){
        res.writeHead(404,{"Content-type":"application/json;charset=UTF-8"});
        res.end("请传入文件地址！");
        return;
    }
    if(htmlFile){
        htmlPath = path.join(__dirname,"public/html",uuid.v1() + ".html");
        console.log(htmlPath);
        let fileBuffer = new Uint8Array(htmlFile.data);
        fs.writeFileSync(htmlPath,fileBuffer);
        params.html = htmlPath;
    }
    try {
        var file = await html2pdf(params);
        res.setHeader('Content-Description',"File Transfer");
        res.setHeader("Content-Type","application/octet-stream");
        res.setHeader("Content-Disposition","attachment; filename="+file.pdfname);
        res.setHeader("Content-Transfer-Encoding","binary");
        console.log(file.data.byteLength,file.data.length);
        res.setHeader("Content-Length",file.data.byteLength);
        res.send(file.data);
        if(htmlFile && htmlPath){
            fs.unlinkSync(htmlPath,(err)=>{
                console.log("文件移除失败！");
            });
        }
        return;
    } catch (error) {
        res.writeHead(404,{"Content-type":"application/json;charset=UTF-8"});
        res.end("文件转换失败");
        console.log(error);
    }
    res.end("结束");
});

app.listen(3000);


